var _CONFIG = {
    TYPE: '',
    JQXGRID: '#jqx_grid_view',
    BINDING_URI: base_url + 'cms/so/config/bindingbytype/',
    EDITPANEL_URI: base_url + 'cms/so/config/editpanel/',
    COMMIT_URI: base_url + 'cms/so/config/oncommit/',
    DELETE_URI: base_url + 'cms/so/config/ondelete/'
};
var _SO = (function() {
    var oTable;
    var that = this;
    var datafields, source, dataAdapter;
    return {
        onCommit: function(Params, Id, callback) {
            /* Commit data lên vào DB, Id>0 là Update, Id=0 hoặc ko có là Insert */
            backend({
                url: _CONFIG.COMMIT_URI,
                data: {
                    Id: Id,
                    Params: Params
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    } else {
                        $.jGrowl(rsdata.message);
                        if (typeof callback == 'function') {
                            callback();
                        }
                    }
                }
            }).call();
        },
        creategrid: function() {
            var dataTypeSource =
                    {
                        datatype: "json", type: "POST",
                        datafields: [
                            {name: 'Id', type: 'int'},
							{name: 'Title'},
							{name: 'Name'},
							{name: 'Value'},
							{name: 'Type'},
							{name: 'Insert', type: 'date'},
							{name: 'Update', type: 'date'}
                        ],
                        root: "rows",
                        id: 'Id',
                        url: "/cms/so/config/bindingbytype/System",
                        async: false
                    };
            var dataTypeAdapter = new $.jqx.dataAdapter(dataTypeSource, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                },
                autoBind: true,
                beforeLoadComplete: function (records) {
                    var tabhtml = records.map(function(record){
						
						var tab = 
							'<li class="'+(record.Value==_CONFIG.TYPE?'active':'')+'">' +
								'<a href="#tab_1" data-toggle="tab" onclick="_SO.onChangeSource(\''+record.Value+'\');">'+ record.Name+'</a>'+
							'</li>'
						;
						console.log(record);
						return tab;
					}).join('\n');
					$('.table-overflow ul.nav.nav-tabs').html(tabhtml);
                    return records;
                }
            });
            datafields = [
                {name: 'Id', type: 'int'},
                {name: 'Title'},
                {name: 'Name'},
				{name: 'Value'},
                {name: 'Type'},
                {name: 'Insert', type: 'date'},
                {name: 'Update', type: 'date'}
            ];
            source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.BINDING_URI + _CONFIG.TYPE,
                root: 'rows'
            };
            dataAdapter = new $.jqx.dataAdapter(source, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
            var columns = [
				{ 	
					text: '', datafield: 'Edit', columntype: 'button', width:40,
					filterable: false, sortable: false, editable: false,
					cellsrenderer: function () {
						 return "Edit";
					}, 
					buttonclick: function (row) {
						var dataRecord = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
						_SO.onEditItem(dataRecord.Id);
					}
				},
				{ 	
					text: '', datafield: 'Delete', columntype: 'button', width:48,
					filterable: false, sortable: false, editable: false,
					cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
						 return "Delete";
					}, 
					buttonclick: function (row,datarow) {
						var dataRecord = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
						_SO.onDeleteItem(dataRecord.Id);
					}
				},
                
				{
                    text: 'Type', dataField: 'Type',hidden:true, //displayfield: 'Name',
                    columntype: 'dropdownlist', filtertype: 'checkedlist',
                    cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) {
                        var str = '<div style="overflow: hidden; text-overflow: ellipsis; padding-bottom: 4px; text-align: left; margin-right: 2px; margin-left: 4px; padding-top: 4px;">';
                        var display = value;
                        for (var i = 0; i < dataTypeAdapter.records.length; i++) {
                            if (dataTypeAdapter.records[i].Value === value) {
                                display = dataTypeAdapter.records[i].Name;
                                break;
                            }
                        }
                        str += display;
                        str += '</div>';
                        return str;
                    },
                    createeditor: function(row, column, editor) {
                        // assign a new data source to the combobox.
                        editor.jqxDropDownList({
                            autoDropDownHeight: true,
                            source: dataTypeAdapter.records, promptText: "Please Choose:",
                            displayMember: 'Name', valueMember: 'Value'
                        });
                    },
                    initeditor: function(row, cellvalue, editor, celltext, pressedkey) {
                        // set the editor's current value. The callback is called each time the editor is displayed.
                        //editor.jqxDropDownList('setContent', celltext); 
                        var items = editor.jqxDropDownList('getItems');
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].value === cellvalue) {
                                editor.jqxDropDownList('selectItem', items[i]);
                                break;
                            }
                        }
                    },
                    geteditorvalue: function(row, cellvalue, editor) {
                        // return the editor's value.
                        return editor.val();
                    }
                },
				
				{
                    text: 'Name', dataField: 'Name'
                },
                {
                    text: 'Title', dataField: 'Title'
                },
                {
                    text: 'Created', dataField: 'Insert', width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: true, editable: false
                },
                {
                    text: 'Modified', dataField: 'Update', width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: true, editable: false
                }
            ];

            $(_CONFIG.JQXGRID).jqxGrid({
                width: '100%', //autoheight:true,
                //height: '100%',
                source: dataAdapter,
                theme: theme, sortable: true,
                filterable: true,
                autoshowfiltericon: true,
                showfilterrow: true,
                editable: true,
                //rowsheight:34,
                showemptyrow: false,
                columns: columns,
                selectionmode: 'singlecell',
                editmode: 'dblclick',
                virtualmode: false,
                //groupable: true,
                rendergridrows: function() {
                    return dataAdapter.records;
                },
                //pageable: true,
                //pagesize: 100,
                //pagesizeoptions: ['100', '200', '500', '1000'],
                ready: function() {
                    //_SO.onFillter('Type',_CONFIG.TYPE);

                    var $refresh = $('<div type="button"  title="Tải lại" style="margin-left: 0px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/view_refresh.png"/></div>');
                    var $option = $('<div type="button"  title="Tùy chỉnh" style="margin-left: 0px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/option.gif"/></div>');
                    var $add = $('<div type="button"  title="Thêm mới" style="margin-left: 4px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/add_1.png"/></div>');
                    $refresh.click(function() {
                        _SO.onRefresh();
                    });
                    $add.click(function() {
                        _SO.onAddItem();
                    });
                    $option.prependTo($(_CONFIG.JQXGRID + ' .jqx-grid-pager>div'));
                    $refresh.prependTo($(_CONFIG.JQXGRID + ' .jqx-grid-pager>div'));
                    $add.prependTo($(_CONFIG.JQXGRID + ' .jqx-grid-pager>div'));

                },
                handlekeyboardnavigation: function(event)
                {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (key == 27) {
                        that.cancel = true;
                    }
                },
            }).bind('cellbeginedit', function(event) {
                that.cancel = false;
            }).bind('cellendedit', function(event) {
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                if (that.cancel)
                    return;
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                try {
                    var args = event.args;
                    var column = args.datafield, _row = args.rowindex, _value = args.value;
                    var _data = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', _row);
                    var _id = _data.Id;
                    if (_id == undefined || _id == "") {
                        return;
                    }
                    switch (column) {
                        case 'Title':
                            if (_value != _data.Title && _value != '')
                                _SO.onCommit({Title: _value}, _id);
                            break;
						case 'Name':
                            if (_value != _data.Name && _value != '')
                                _SO.onCommit({Name: _value}, _id);
                            break;
                        case 'Type':
                            if (_value != _data.Type)
                                _SO.onCommit({Type: _value}, _id);
                            break;
                        case 'Active':
                            if (_value)
                                _SO.onCommit({Active: 'true'}, _id);
                            else
                                _SO.onCommit({Active: 'false'}, _id);
                            break;
                        default:
                            $.jGrowl("Chưa mở tính năng sửa trực tiếp cột này", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }
                } catch (e) {
                    $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    //bckdialog({type:'error'}).open(e.message);
                }
            });
        },
        onInit: function() {
            this.creategrid();
        },
        onAddItem: function() {
            this.onEditItem(0);
        },
        onEditItem: function(Id) {
            if (PENDING)
                return false;
            $('#dialog-edit-panel>.base-dialog-modal').html('<div class="base_loading" style="display: block;height: 60px"></div>');
            bckdialog({
                title: 'ADD / EDIT',
                message: $('#dialog-edit-panel'),
                buttons: [
                    {
                        text: 'DONE',
                        class: 'base_button base_green base-small-border-radius',
                        click: function() {
                            _SO.onSave();
                        }
                    },
                    {
                        text: 'CLOSE',
                        class: 'base_button base_red base-small-border-radius',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            }).open();
            backend({
                url: _CONFIG.EDITPANEL_URI + _CONFIG.TYPE,
                data: {
                    Id: Id
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $('#dialog-edit-panel>.base-dialog-modal').html('<span style="color:red">' + rsdata.message + '</span>');
                    } else {
                        $('#dialog-edit-panel>.base-dialog-modal').html(rsdata.htmlreponse);
                        $('#dialog-edit-panel').dialog('close').dialog('open');
                        $('#_form_edit_panel select').select2();
                        _SO.onTypeChange();
                        $('#_form_edit_panel select[name="Type"]').change(function() {
                            _SO.onTypeChange();
                        });
                    }
                }
            }).call();
        },
        onTypeChange: function() {
            var type = $('#_form_edit_panel select[name="Type"]').val();
            if (type === "Image") {
                $('#_form_edit_panel [name="Source"]').parent().prev().html('Hình ảnh');
                $('#_form_edit_panel [name="Source2"]').parents('.control-group').hide();
                $('#_form_edit_panel [name="Link"]').parents('.control-group').show();
            }
            if (type === "Youtube") {
                $('#_form_edit_panel [name="Source2"]').parent().prev().html('Mã Youtube');
                $('#_form_edit_panel [name="Source2"]').parents('.control-group').show();
                $('#_form_edit_panel [name="Link"]').parents('.control-group').hide();
            }
            if (type === "Video") {
                $('#_form_edit_panel [name="Source2"]').parent().prev().html('Mã nhúng');
                $('#_form_edit_panel [name="Source2"]').parents('.control-group').show();
                $('#_form_edit_panel [name="Link"]').parents('.control-group').hide();
            }
            if (type === "File") {
                $('#_form_edit_panel [name="Source2"]').parents('.control-group').hide();
                $('#_form_edit_panel [name="Link"]').parents('.control-group').show();
            }
            if (type === "Other") {
                $('#_form_edit_panel [name="Source"]').parent().prev().html('Hình ảnh');
                $('#_form_edit_panel [name="Source2"]').parent().prev().html('Nguồn');
                $('#_form_edit_panel [name="Source2"]').parents('.control-group').show();
                $('#_form_edit_panel [name="Link"]').parents('.control-group').show();
            }
        },
        onSave: function() {
            if ($('#_form_edit_panel').validationEngine('validate') === false)
                return false;
            var Params = $('#_form_edit_panel').serializeObject();
            $("#dialog-edit-panel").parents('.ui-dialog').find('.dialog-pending').show();
            this.onCommit(Params, $('#Id').val(), function() {
                $("#dialog-edit-panel").parents('.ui-dialog').find('.dialog-pending').hide();
                _SO.onCancel();
                _SO.onRefresh();
            });
            return false;
        },
        onCancel: function() {
            $('#dialog-edit-panel').dialog('close');
        },
        onDeleteItem: function(Id) {
            backend_delete(_CONFIG.DELETE_URI, Id, function() {
                _SO.onRefresh();
            });
        },
        onRefresh: function() {
            //oTable.fnDraw(false);
            $(_CONFIG.JQXGRID).jqxGrid('updatebounddata');
        },
        onFillter: function(datafield, filtervalue) {
            if (filtervalue == '') {
                $(_CONFIG.JQXGRID).jqxGrid('removefilter', datafield, true);
                return;
            }
            var filtertype = 'stringfilter';
            var filtergroup = new $.jqx.filter();
            var filter_or_operator = 1;
            var filtercondition = 'contains';
            var filter = filtergroup.createfilter(filtertype, filtervalue, filtercondition);
            filtergroup.addfilter(filter_or_operator, filter);

            //$(grid_element).jqxGrid('clearfilters');
            // add the filters.
            $(_CONFIG.JQXGRID).jqxGrid('addfilter', datafield, filtergroup);
            // apply the filters.
            $(_CONFIG.JQXGRID).jqxGrid('applyfilters');
        },
        onChangeSource: function(type) {
            if(type===_CONFIG.TYPE)return;
			_CONFIG.TYPE = type;
            source.url = _CONFIG.BINDING_URI + _CONFIG.TYPE;
            this.onRefresh();
        }
    };
}());